package com.siro.auth.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siro.auth.base.common.domain.PageRequest;
import com.siro.auth.base.config.ModelServiceConfig;
import com.siro.auth.entity.FetchModel;
import com.siro.auth.service.IInspPlanRlnToolService;
import com.siro.auth.utils.http.HttpChl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author starsea
 * @date 2022-12-14 19:35
 */
@Service
public class InspPlanRlnToolServiceImpl implements IInspPlanRlnToolService {

    private static Logger log = LoggerFactory.getLogger(InspPlanRlnToolServiceImpl.class);

    @Autowired
    private ModelServiceConfig modelServiceConfig;

    /**
     * 调用外系统返回数据 组装成分页数据回显给前端
     *
     * @param pageRequest
     * @return
     */
    @Override
    public Object getRuleAndModel(PageRequest pageRequest) {
        String url = "/api/onModels";
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("sysId", "TOINS");
        jsonObject.set("pagenum", Integer.valueOf((int) pageRequest.getPage().getCurrent()));
        long starTime = System.currentTimeMillis();
        IPage<FetchModel> page = getData(url, "GET", jsonObject);
        long cosTime = System.currentTimeMillis() - starTime;
        log.info("调用外系统完成，耗时：{}毫秒", cosTime);
        return page;
    }

    /**
     * 异步创建任务
     */
    @Async("taskExecutor")
    @Override
    public void asynsBatchCreateIsueTasks() {
        log.info("这是一个异步任务");
    }

    private IPage<FetchModel> getData(String url, String method, JSONObject data) {
        String reqcod = String.format("%s%s?sysId=%s&pagenum=%s", modelServiceConfig.getUrl(), url, data.get("sysId"), data.get("pagenum"));
        log.info("调用外系统，请求API地址：{}",reqcod);
        String jsonStr = HttpChl.httpReq(reqcod, method, data, null);
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        Object content = jsonObject.get("content");
        Object data1 = JSONUtil.parseObj(content).get("data");
        JSONArray objects = JSONUtil.parseArray(data1);

        List<FetchModel> fetchModels = JSONUtil.toList(objects, FetchModel.class);

        IPage<FetchModel> page = new Page<>();
        page.setRecords(fetchModels);
        Integer pagenum = (Integer) data.get("pagenum");
        page.setCurrent(new Long(pagenum));
        page.setTotal((long)fetchModels.size());
        return page;
    }
}
